package dieLock;

/**
 * 死锁Demo
 */
public class DieLock {

    public static void main(String[] args) {
        String string1 = "string1";
        String string2 = "string2";
        Thread thread1 = new Thread(new Thread1(string1, string2));
        Thread thread2 = new Thread(new Thread2(string1, string2));
        thread1.start();
        thread2.start();

    }

    static class Thread1 implements Runnable{
        String string1;
        String string2;
        public Thread1(String string1 ,String string2 ){
            this.string1 = string1;
            this.string2 = string2;
        }

        @Override
        public void run() {
            synchronized (string1){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (string2){
                    System.out.println(string2);
                }
            }
        }
    }

    static class Thread2 implements Runnable{
        String string1;
        String string2;
        public Thread2(String string1 ,String string2){
            this.string1 = string1;
            this.string2 = string2;
        }

        @Override
        public void run() {
            synchronized (string2){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (string1){
                    System.out.println(string2);
                }
            }
        }
    }
}
